package com.thb.business.dao.Impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.thb.business.dao.IArticleStoreDao;
import com.thb.business.model.Article;
import com.thb.business.model.ArticleStore;

@Repository
public class IArticleStoreDaoImpl implements IArticleStoreDao {

	@Autowired
	private JdbcTemplate jTemplate;

	@Override
	public List<Article> findByPara(ArticleStore para) {
		StringBuilder sql = new StringBuilder("");
		sql.append("select a.* from t_article a join t_article_store b on a.id = b.article_id and b.uid = ? limit ?,?");
		Object[] arg = new Object[]{para.getUid(),(para.getPage()-1)*para.getPageSize(),para.getPageSize()};
		
		return jTemplate.query(sql.toString(), arg,new RowMapper<Article>() {
			
			@Override
			public Article mapRow(ResultSet rs, int no) throws SQLException {

				return jsonMapper(rs, no);
			}
		});
	}

	private Article jsonMapper(ResultSet rs, int no) throws SQLException {

		Article vo = new Article();
		vo.setId(rs.getInt("id"));
		vo.setTitle(rs.getString("title"));
		vo.setContent(rs.getString("content"));
		vo.setCreateTime(rs.getString("create_time"));
		vo.setHotType(rs.getInt("hot_type"));
		vo.setImg1(rs.getString("img1"));
		vo.setImg2(rs.getString("img2"));
		vo.setImg3(rs.getString("img3"));
		vo.setType(rs.getInt("type"));
		vo.setSource(rs.getString("source"));
		
		return vo;
	}

	@Override
	public int countByPara(ArticleStore para) {
		StringBuilder sql = new StringBuilder("");
		sql.append("select a.* from t_article a join t_article_store b on a.id = b.article_id and b.uid = ?");
		Object[] arg = new Object[]{para.getUid()};
		return jTemplate.queryForInt(sql.toString(), arg);
	}

	@Override
	public int add(ArticleStore para) {
		StringBuilder sql = new StringBuilder("");
		sql.append("insert into t_article_store(article_id,uid) values(?,?)");
		return jTemplate.update(sql.toString(), para.getArticleId(),para.getUid());
	}

	@Override
	public int delete(ArticleStore para) {
		StringBuilder sql = new StringBuilder("");
		sql.append("delete from t_article_store where article_id = ? and uid = ?");
		return jTemplate.update(sql.toString(), para.getArticleId(),para.getUid());
	}

	

}
